<template>
<div class="map-container">
    <button class="select-button" @click="showExist()">显示已划分网格</button>
    <button class="clear-button" @click="clearCoordinate()">清除</button>
    <button class="continue-button" @click="continueCoordinate()">继续</button>
    <select id="gridLevelSelect" class="top-right-select">
        <option value="2">区县级网格</option>
        <option value="3">乡镇街道级网格</option>
        <option value="4">社区级网格</option>
        <option value="5">末级网格</option>
    </select>
    <div id="mapDiv" class="mapDiv"></div>

    <input id="area" style="display: none;">
    <input id="acreage" style="display: none;">
</div>
</template>
<script>
import {loadScript, loadCss,loadModules} from 'esri-loader';
import website from '@/config/website';
import $ from 'jquery';
import "@/assets/css/gis/coordinate.css";
var map,
    draw, 
    drawEvent, 
    orGraphics, 
    graphicsLayer, 
    selectedGridFillSymbol, 
    gridFillSymbol,
   
    selectClickEvent
export default {
     name: 'grid-map',
 data() {
      return {
          gridId: "370104008006001",
          typename: "GIS_GRID2"
      };
    },
mounted() {
    let _this = this;
   // console.log(website.CssUrl);
    loadScript({ url: website.InitUrl})
    loadCss(website.CssUrl)
    loadModules([
                "esri/map", 
                "esri/layers/ArcGISTiledMapServiceLayer", 
                "esri/layers/GraphicsLayer",
                "esri/symbols/SimpleFillSymbol",
                "esri/symbols/SimpleLineSymbol",
                "esri/Color",
                "esri/geometry/Polygon",
                "esri/graphic",
                "esri/units",
                "esri/graphicsUtils",
                "esri/geometry/geodesicUtils",
                "dojo/domReady!"
            ], { css: true })
            .then(([
                 Map, 
                 ArcGISTiledMapServiceLayer,
                 GraphicsLayer,
                 SimpleFillSymbol,
                 SimpleLineSymbol,
                 Color,
                 Polygon,
                 Graphic,
                 units,
                 graphicsUtils,
                 geodesicUtils

            ]) => {
                //实例化地图
                map = new Map("mapDiv", {
                center: website.MapCenterPoint,
                zoom: 12,
                slider: false, //缩放按钮移除
                logo: false, //logo移除
                isDoubleClickZoom: false,
                });
                //加载图层
                let mapServer = new ArcGISTiledMapServiceLayer(website.BaseMapUrl)
                map.addLayer(mapServer)
                 //地图网格范围层
                graphicsLayer = new GraphicsLayer({id: "graphicsLayer"});
                map.addLayer(graphicsLayer);
                graphicsLayer.hide();
                console.log("==============地图底图加载完成===========");
                map.on("load", function () {
                  _this.getGridList(_this.typename,Polygon,Graphic);//地图数据
                  _this.showDrawGrid(Polygon,Graphic,graphicsUtils,units,geodesicUtils);
                });
                map.on("extent-change", function (e) {
                    mapExtentChange(e);
                });
                gridFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT,
                new Color([0, 0, 205]), 2), new Color([0, 0, 0, 0.25]));

                selectedGridFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT,
                new Color([0, 0, 245]), 2), new Color([0, 0, 0, 0.5]));
              $("#gridLevelSelect").change(function(){
                  console.log("看看选中的数字是几="+$(this).val());
                  _this.typename = 'GIS_GRID' + $(this).val();
                  console.log(_this.typename);
                  console.log("1");
                  _this.getGridList(_this.typename,Polygon,Graphic);
              });
              function mapExtentChange() {
                   console.log("2");
                   console.log(_this.typename);
                  _this.getGridList(_this.typename,Polygon,Graphic);
              }
            
        })
  },
  methods: {
      //加载地图数据
        getGridList(typename,Polygon,Graphic) {
            graphicsLayer.clear();
            console.log("000-"+typename);
            var baseUrl = 'http://192.168.3.100:8091/nxzserver' + '/cite/ows?service=WFS&version=1.1.0&request=GetFeature&typename=' + typename + '&outputFormat=json&maxFeatures=8000&filter=%3CFilter%20xmlns:ogc=%22http://www.opengis.net/ogc%22%20xmlns:gml=%22http://www.opengis.net/gml%22%3E%3CIntersects%3E%20%3CPropertyName%3Egeom%3C/PropertyName%3E%20%3Cgml:Envelope%20srsName=%22EPSG:4326%22%3E%09%20%3Cgml:lowerCorner%3E';
            baseUrl += map.extent.xmin;
            baseUrl += '%20' + map.extent.ymin;
            baseUrl += '%3C/gml:lowerCorner%3E%20%09%20%3Cgml:upperCorner%3E' + map.extent.xmax;
            baseUrl += '%20' + map.extent.ymax;
            baseUrl += '%3C/gml:upperCorner%3E%20%3C/gml:Envelope%3E%3C/Intersects%3E%3C/Filter%3E';
            console.log("baseUrl======="+baseUrl);
            $.ajax({
                type: 'post',
                url: baseUrl,
                dataType: 'json',
                success: function (result) {
                    var featureSet = result.features;
                    for (var i = 0; i < featureSet.length; i++) {
                        var obj = featureSet[i];
                        var polygonJson;
                        if (obj.geometry.type === "Polygon") {
                            polygonJson = {"rings": obj.geometry.coordinates, "spatialReference": {"wkid": 4326}};
                        } else {
                            var geoArr = [];
                            for (var n = 0; n < obj.geometry.coordinates.length; n++) {
                                geoArr.push(obj.geometry.coordinates[n][0]);
                            }
                            polygonJson = {"rings": geoArr, "spatialReference": {"wkid": 4326}};
                        }
                        var polygon = new Polygon(polygonJson);
                        var gra = new Graphic(polygon, gridFillSymbol, obj.properties);
                        graphicsLayer.add(gra);
                    }
                }
            });
        },
        showExist() {
            console.log("显示已划分网格");
            graphicsLayer.show();
        },
        //加载地图数据
        showDrawGrid(Polygon,Graphic,graphicsUtils,units,geodesicUtils) {
            let _this =this;
            console.log("加载地图数据0");
            console.log("gridid=="+_this.gridId);
            if (!_this.gridId) {
                _this.getCoordinatePoint();
            } else {
                var layer = "GIS_GRIDALL";
                var appendParam = "GRID_ID=" + _this.gridId;
                var baseUrl = 'http://192.168.3.100:8092/nxzserver' + '/cite/ows?service=WFS&version=1.1.0&request=GetFeature&typename=' + layer + '&outputFormat=json&maxFeatures=8000';
                baseUrl += "&cql_filter=" + appendParam;
                console.log("layer--baselUrl=="+baseUrl);
                $.ajax({
                    type: 'post',
                    url: baseUrl,
                    dataType: 'json',
                    success: sucFunction
                });
                function sucFunction(result){
                    if (result.features && result.features.length === 1) {
                        var obj = result.features[0];
                        var polygonJson;
                        if (obj.geometry.type === "Polygon") {
                            polygonJson = {"rings": obj.geometry.coordinates, "spatialReference": {"wkid": 4326}};
                        } else {
                            var geoArr = [];
                            for (var n = 0; n < obj.geometry.coordinates.length; n++) {
                                geoArr.push(obj.geometry.coordinates[n][0]);
                            }
                            polygonJson = {"rings": geoArr, "spatialReference": {"wkid": 4326}};
                        }
                        var polygon = new Polygon(polygonJson);
                        if (!orGraphics) {
                            orGraphics = new Graphic(polygon, selectedGridFillSymbol, {});
                            map.graphics.add(orGraphics);
                        } else {
                            orGraphics.setGeometry(polygon);
                        }
                        map.setExtent(graphicsUtils.graphicsExtent([orGraphics]), true);
                        console.log("0090-11");
                        _this.setValue(orGraphics,geodesicUtils,units);
                    } else {
                        console.log("0090-22");
                        _this.getCoordinatePoint();
                    }
                }
                
            }
        },

        /**
         * 从地图获取点位。
         *
         */
        getCoordinatePoint() {
            loadModules([
                "esri/graphic",
                "esri/toolbars/draw", 
                "dojo/on",  
                "esri/units",
                "esri/geometry/geodesicUtils"
            ], { css: true })
            .then(([Graphic,Draw,on,units,geodesicUtils]) => {
                let _this =this;
                    draw = new Draw(map, {showTooltips: true});
                    draw.activate(Draw.POLYGON);
                    //要操作的graphic
                    drawEvent = on(draw, "draw-complete", function (result) {
                        if (!orGraphics) {
                            orGraphics = new Graphic(result.geometry, selectedGridFillSymbol, {});
                            map.graphics.add(orGraphics);
                        }

                        console.log("0092",_this)
                        _this.setValue(orGraphics,geodesicUtils,units);
                        //关闭绘图对象
                        draw.deactivate();
                        drawEvent.remove();

                        

                    });
                });
        },
        setValue(orGraphics,geodesicUtils,units) {
            console.log("这是一个方法啊");
                var geo = "";
                var acreage = 0;
                if (orGraphics && orGraphics.geometry && orGraphics.geometry.rings) {
                    acreage = geodesicUtils.geodesicAreas([orGraphics.geometry], units.SQUARE_METERS);
                    geo = JSON.stringify(orGraphics.geometry.rings);
                }
                document.getElementById("area").value = geo;
                document.getElementById("acreage").value = acreage;
        },
        /**
         * 对于多分区网格，继续划分网格的下一个范围。
         */
        continueCoordinate() {
            loadModules([
                "esri/graphic", 
                "esri/toolbars/draw", 
                "dojo/on",
                "esri/units",
                "esri/geometry/geodesicUtils"
            ], { css: true })
            .then(([Graphic,  Draw, on,units,geodesicUtils]) => {             
                let _this = this;   
                    if (!draw)
                        draw = new Draw(map, {showTooltips: true});
                    draw.activate(Draw.POLYGON);
                    if (drawEvent)
                        drawEvent.remove();

                    drawEvent = on(draw, "draw-complete", function (result) {
                        if (!orGraphics) {
                            orGraphics = new Graphic(result.geometry, selectedGridFillSymbol, {});
                            map.graphics.add(orGraphics);
                        } else {
                            orGraphics.geometry.rings.push(result.geometry.rings[0]);
                        }
                        map.graphics.refresh();
                        console.log("0093")
                        _this.setValue(orGraphics,geodesicUtils,units);
                        //关闭绘图对象
                        draw.deactivate();
                        drawEvent.remove();
                    });
                });
        },
        /**
         * 清除已划分的网格区域。
         */
        clearCoordinate() {
            if (selectClickEvent)
                selectClickEvent.remove();
            if (orGraphics) {
                orGraphics.geometry.rings = [];
                map.graphics.refresh();
           }
        }
  },
  beforeDestroy() {
    if (this.view) {
      this.view.container = null
    }
  },
}
</script>
 
<style lang="scss" scoped>

</style>